package com.dashboard.sync.service;

import cn.hutool.core.collection.CollectionUtil;
import com.dashboard.biz.UserService;
import com.dashboard.common.utils.R;
import com.dashboard.entity.WarningJob;
import com.dashboard.mapper.WarningJobMapper;
import com.dashboard.sync.pool.HotListPoolExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author xuxiao
 */
@Service
@Slf4j
public class HotListTaskService {

    private volatile HotListPoolExecutor hotListPoolExecutor = new HotListPoolExecutor();

    private volatile AtomicBoolean bool = new AtomicBoolean(true);

    @Resource
    UserService userService;

    @Resource
    WarningJobMapper warningJobMapper;

    public R registerNewTaskToRun(WarningJob warningJob){
        try{
            boolean b = hotListPoolExecutor.addHotListJob(warningJob);
            return b?R.ok():R.error("生产热榜消息失败");
        }catch(Exception e){
            log.error("生产热榜消息失败",e);
            return R.error("生产热榜消息失败").setData(e);
        }
    }
    public synchronized void initHotList(){
        List<WarningJob> warningJobList =  this.warningJobMapper.selectAll();
        if(CollectionUtil.isEmpty(warningJobList)){
           return;
        }
        warningJobList.stream().forEach(hotListPoolExecutor::addHotListJob);
    }

    public void runAllRegisterHotListTask()
    {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(()->{
            while (!bool.get()){
                executorService.shutdown();
            }
            try {
                hotListPoolExecutor.consumerAllHotJobs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }


    public void showdownHotList()
    {
        if (userService.isSuper()){
            bool.compareAndSet(false,true);
            hotListPoolExecutor.showdown();
        }
    }


}
